package com.gmg.tools;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONObject;

public class ServerConnection {

	public static final String URL_SERVER = "http://luffy.hd.free.fr:8080/GoogleMapServer/";
//	public static final String URL_SERVER = "http://192.168.1.15:8080/GoogleMapServer/";
	
	private static final String USER_CREATED = "userCreated";
	private static final Object YES = "yes";
	private static final Object NO = "no";
	private static final String ERROR_CREATION_CODE = "errorCode";
	
	public static int createUser(String username, String password, String mail) throws Exception {
		
		URL url = new URL(URL_SERVER + "CreateUser?name=" + username + "&password=" + password + "&mail=" + mail);
		
		System.out.println(url.toString());
		
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		
		System.out.println(connection.getResponseCode());
		
		if (connection.getResponseCode() / 100 != 2) {
			throw new IOException("Response not OK Version"+ connection.getResponseCode());
		}

		InputStreamReader in = new InputStreamReader(connection.getInputStream());
		BufferedReader reader = new BufferedReader(in);
		
		StringBuffer sbf = new StringBuffer();
		String line = null;
		
		while ((line = reader.readLine()) != null) {
			sbf.append(line);
		}

		JSONObject jsonObject = new JSONObject(sbf.toString());

		if (jsonObject.getString(USER_CREATED).equals(YES))
			return 0;
		if (jsonObject.getString(USER_CREATED).equals(NO))
		{
			return jsonObject.getInt(ERROR_CREATION_CODE);
		}
		return -1;
	}
}
